﻿using System.Reflection;
using System.Text;
using rpc_service.cache;
using rpc_service.core.interceptor;

namespace rpc_service.core.support.assembly.roslyn;

public class RoslynMethodGetHttpMethodStep : RoslynMethodBaseStep
{
    public RoslynMethodGetHttpMethodStep(List<Type> interceptors, Type pollType, Type registryType) : base(interceptors, pollType, registryType)
    {
        
    }
    
    protected override bool isPass(string httpMethod, Type returnType)
    {
        if (httpMethod != "GET")
        {
            return false;
        }

        return true;
    }

    protected override StringBuilder execute(StringBuilder stringBuilder, Type targetType, MethodInfo targetMethod)
    {
        generateMethod(stringBuilder, targetMethod, (builder, isTask) =>
        {
            generateHttpClient(builder, targetType, targetMethod, isTask, (builder, isTask) =>
            {
                generateTryCatch(builder, isTask, (builder, isTask) =>
                {
                    Type stringType = "string".GetTypeByStr();
                    
                    // 发起请求
                    if (isTask)
                    {
                        builder.AppendLine(
                            "HttpResponseMessage response = await client.GetAsync(urlBuilder.ToString());");
                        // 检查响应状态码，确保请求成功
                        builder.AppendLine("response.EnsureSuccessStatusCode();");
                        builder.AppendLine($@"{stringType} responseBody = await response.Content.ReadAsStringAsync();");
                    }
                    else
                    {
                        builder.AppendLine(
                            "HttpResponseMessage response = client.GetAsync(urlBuilder.ToString()).Result;");
                        // 检查响应状态码，确保请求成功
                        builder.AppendLine("response.EnsureSuccessStatusCode();");
                        builder.AppendLine($@"{stringType} responseBody = response.Content.ReadAsStringAsync().Result;");
                    }

                    generateReturn(builder, targetType, targetMethod, isTask);
                });
            });
        });
        
        return stringBuilder;
    }
}